﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace P2PChat.Client.UI
{
    /// <summary>
    /// WinRegist.xaml 的交互逻辑
    /// </summary>
    public partial class WinRegist : Window
    {
        public WinRegist()
        {
            InitializeComponent();
        }

        private void btn_Regist_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 判断输入的有效性.
                Regex emailCheck = new Regex(@"(?<name>\S+)@(?<domain>\S+)"),
                    pwdCheck = new Regex(@"[\w\d][\w\d_.*]{4,126}[\w\d]");
                if (!emailCheck.Match(txt_Username.Text).Success)
                {
                    throw new FormatException("电子邮件地址格式不正确");
                }
                if (!pwdCheck.Match(txt_Password.Password.Trim()).Success)
                {
                    throw new FormatException("密码格式不正确");
                }
                if (txt_Password.Password.Trim() != txt_ConfirmPassword.Password.Trim())
                {
                    throw new FormatException("确认密码和密码不一致!");
                }

                // 向服务器提出注册请求
                // 需要创建新线程以完成该操作
                new System.Threading.Thread(threadMain_DoRegist).Start();
            }
            catch (FormatException ex)
            {
                lb_RegistProgress.Content = "错误:" + ex.Message;
            }
            finally
            {
            }
            

        }

        private void threadMain_DoRegist()
        {

            // 封印控件
            ui_isEnable(false);

            try
            {
                // 获取相关值, 创建相关数据包
                lb_RegistProgress.Dispatcher.Invoke(new Action(() =>
                {
                    lb_RegistProgress.Content = "正在处理信息";
                }));
                string txt_Email_Value = null, pwdHash = null;
                txt_Username.Dispatcher.Invoke(new Action(() =>
                {
                    txt_Email_Value = txt_Username.Text.Trim();
                }));
                txt_Password.Dispatcher.Invoke(new Action(() =>
                {
                    new P2PChat.Security.Hasher.MD5Hash().ComputeHash(
                        Encoding.UTF8.GetBytes(txt_Password.Password.Trim()), out pwdHash);
                }));

                P2PChat.Data.Packets.RegistPacket p = new P2PChat.Data.Packets.RegistPacket()
                {
                    emailAddress = txt_Email_Value,
                    password = pwdHash,
                };
                P2PChat.Data.NetPacket pack_Regist = new P2PChat.Data.NetPacket()
                {
                    Tag = P2PChat.Data.PacketTag.Regist,
                    Content = p,
                };
                MemoryStream ms = new MemoryStream();
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(ms, pack_Regist);

                // 向服务器传输数据
                using (System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient())
                {
                    lb_RegistProgress.Dispatcher.Invoke(new Action(() =>
                    {
                        lb_RegistProgress.Content = "正在连接服务器";
                    }));

                    try
                    {
                        c.SendTimeout = 15 * 1000;
                        c.Connect(GlobalConfig.ServerHost, GlobalConfig.ServerPort);
                        
                        // 发送数据
                        lb_RegistProgress.Dispatcher.Invoke(new Action(() =>
                        {
                            lb_RegistProgress.Content = "注册";
                        }));
                        c.Client.Send(ms.GetBuffer());

                        // 接收服务器的返回包
                        P2PChat.Data.NetPacket packet = (P2PChat.Data.NetPacket)bf.Deserialize(c.GetStream());
                        if (packet.Tag == P2PChat.Data.PacketTag.ServerException)
                        {
                            throw new Exception("服务器端出现了处理异常, 过程被中断.");
                        }
                        else if (packet.Tag == P2PChat.Data.PacketTag.RegistResult)
                        {
                            P2PChat.Data.Packets.RegistResultPacket result =
                                packet.Content as P2PChat.Data.Packets.RegistResultPacket;
                            if (result.ResultCode == 0)
                            {
                                MessageBox.Show("注册成功!", "提示", MessageBoxButton.OK);
                                this.Dispatcher.Invoke(new Action(() =>
                                {
                                    this.Close();
                                }));
                            }
                            else
                            {
                                // 抛出错误原因
                                throw new Exception(result.Result);
                            }
                        }
                        else
                        {
                            throw new Exception("服务器返回了不正确的数据!");
                        }
                    }
                    catch (Exception ex)
                    {
                        lb_RegistProgress.Dispatcher.Invoke(new Action(() =>
                        {
                            lb_RegistProgress.Content = "注册失败: " + ex.Message;
                        }));
                    }
                }

            }
            catch (Exception ex)
            {

            }


            ui_isEnable(true);
        }

        #region 界面操作方法
        // 设定界面控件的可访问性
        private delegate void ui_isEnableDelegate(bool isEnable);
        private void ui_isEnable(bool isEnable)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.Invoke(new ui_isEnableDelegate(ui_isEnable), isEnable);
            }
            else
            {
                txt_Username.IsEnabled =
                txt_Password.IsEnabled =
                txt_ConfirmPassword.IsEnabled =
                btn_Regist.IsEnabled = isEnable;
            }
        }
        #endregion
    }
}
